//package com.example.demo.config;
//
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
//import com.example.demo.entity.TenantConfigEntity;
//import com.example.demo.handle.DataSourceContextHolder;
//import com.example.demo.mapper.TenantConfigMapper;
//import com.example.demo.util.DataSourceUtil;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.ApplicationContext;
//import org.springframework.context.annotation.Lazy;
//import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
//import org.springframework.util.StringUtils;
//
//import javax.sql.DataSource;
//
//public class DynamicDataSource extends AbstractRoutingDataSource {
//
//    @Autowired
//    private ApplicationContext applicationContext;
//
//    @Lazy
//    @Autowired
//    private DynamicDataSourceSummoner summoner;
//
//    @Lazy
//    @Autowired
//    private TenantConfigMapper tenantConfigDAO;
//
//    @Override
//    protected String determineCurrentLookupKey() {
//        String tenantKey = DataSourceContextHolder.getDataSourceKey();
//        return DataSourceUtil.getDataSourceBeanKey(tenantKey);
//    }
//
//    @Override
//    protected DataSource determineTargetDataSource() {
//        String tenantKey = DataSourceContextHolder.getDataSourceKey();
//        String beanKey = DataSourceUtil.getDataSourceBeanKey(tenantKey);
//        if (!StringUtils.hasText(tenantKey) || applicationContext.containsBean(beanKey)) {
//            return super.determineTargetDataSource();
//        }
//        if (tenantConfigDAO.exists(new LambdaQueryWrapper<TenantConfigEntity>().eq(TenantConfigEntity::getTenantKey, beanKey))) {
//            summoner.registerDynamicDataSources();
//        }
//        return super.determineTargetDataSource();
//    }
//}
